import SwiftUI
import CryptoKit
import Zip
import AVFoundation
import Foundation
import math_h
struct ContentBodyView: View {
    var body: some View {
        ZStack{
            Color.clear
        }
    }
}
struct ItemInfoData{
    var listData: [Int] = []
    var list1: [Int] = []
    var list2: [Int] = []
    var list4: [Int] = []
    var list8: [Int] = []
}
//小号 170*170
//中号 364 * 170
//大号 364 * 382
struct ContentView: View {
    @State private var listData: [Item] = []
    @State private var listDataInfo: [ItemInfo] = []
    @State private var currentPage: Int = 0
    @State var isLogo: Bool = false
    @State var isLogo2: Bool = false
    var body: some View {
        let r = 1.3
        let w = 535.0
        let h = 590.0
        ZStack{
            Color.red
            ZStack{
                ZStack(alignment: .topTrailing) {
                    Color.clear
                    if let url1{
                        ISTutorialVideoView(videoUrl: url1,showSound: false)
                            .aspectRatio(484 / 1012, contentMode: .fit)
                            .frame(width: 484/2*r,height: 1012/2*r)
    
                            .mask(ZStack{
                                Image("launch_bottom_mask2").resizable().scaledToFill().frame(width: 484/2*r,height: 1012/2*r)
                            })
                            .padding(.top,44*r)
                            .padding(.trailing,-10*r)
                    }
                }.frame(width: w,height: h).compositingGroup()
                ZStack(alignment: .topLeading) {
                    Color.clear
                    if let url1{
                        ISTutorialVideoView(videoUrl: url1,showSound: false)
                            .aspectRatio(484 / 1012, contentMode: .fit)
                            .frame(width: 484/2*r,height: 1012/2*r)
                            .mask(ZStack{
                                Image("launch_bottom_mask2").resizable().scaledToFill().frame(width: 484/2*r,height: 1012/2*r)
                            })
                            .padding(.top,120*r)
                            .padding(.leading,-13*r)
                    }
                }.frame(width: w,height: h).compositingGroup()
            }.padding(.horizontal).compositingGroup()
                .mask(ZStack{
                    Image("launch_bottom_mask5").resizable().scaledToFit().frame(width: w, height: h, alignment: .center)
                })
        }.frame(width: w,height: h).onAppear {
            for i in 1...10{
                getUUIDGroup(i)
            }
        }
    }
    let uuid = UUID().uuidString
    public func getUUIDGroup(_ group: Int)->Int?{
        let listData: [String] = uuid.components(separatedBy: "-")
        if let last = listData.last{
            debugPrint(last)
            let start = (group-1)*2
            let end = start + 2
            if last.count > start && last.count > end{
                let id = last[start..<end]
                debugPrint(id)
            }
        }
        return nil
    }
    
    var url1: URL?{
        let url = Bundle.main.url(forResource: "视频1_batch", withExtension: "mp4")
        return url
    }
    var url2: URL?{
        let url = Bundle.main.url(forResource: "视频3_batch", withExtension: "mp4")
        return url
    }
}
extension String{
    func string(in range: Range<Int>) -> String {
        return String(self[self.index(self.startIndex, offsetBy: range.lowerBound)..<self.index(self.startIndex, offsetBy: range.upperBound)])
    }
    subscript(r: Range<Int>) -> String {
        get {
            let start = index(startIndex, offsetBy: r.lowerBound)
            let end = index(startIndex, offsetBy: r.upperBound)
            return String(self[start..<end])
        }
    }

}
struct ISTutorialVideoView: View {
    var showSound: Bool = true
    @State private var player: AVPlayer
    @State private var isMute = true
    
    init(videoUrl: URL, isMute: Bool = true, showSound: Bool = true) {
        self.player = AVPlayer(url: videoUrl)
        self.isMute = isMute
        self.showSound = showSound
    }
    
    var body: some View {
        ISVideoPreviewView(player: $player)
            .overlay(
                Button {
                    if isMute {
                        player.volume = 1
                    } else {
                        player.volume = 0
                    }
                    isMute = player.volume == 0
                } label: {
                    let icon = isMute ? "speaker.slash.fill" : "speaker.fill"
                    Image(systemName: icon).resizable().renderingMode(.template)
                        .scaledToFit()
                        .frame(width: 15, height: 15)
                        .frame(width: 50, height: 50)
                        .foregroundColor(.white)
                        .shadow(color: .black, radius: 5)
                        .id(isMute)
                        .transition(.identity)
                }.opacity(showSound ? 1 : 0),
                alignment: .bottomTrailing
            )
            .onAppear {
                isMute = player.volume == 0
            }
    }
}

struct ISVideoPreviewView: View {
    
    @Binding var player: AVPlayer
    
    var body: some View {
        ZStack {
            Color.clear
            _ISVideoPreviewView(player: $player)
        }
        .onAppear {
            // 环绕音
            try? AVAudioSession.sharedInstance().setCategory(.ambient)
            
            player.volume = 0
            player.currentItem?.seek(to: .zero, completionHandler: nil)
            player.play()
        }
        .onDisappear {
            player.pause()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name.AVPlayerItemDidPlayToEndTime)) { note in
            if (note.object as? AVPlayerItem) == player.currentItem {
                player.currentItem?.seek(to: .zero, completionHandler: nil)
                player.play()
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: UIScene.willEnterForegroundNotification)) { _ in
            if player.rate == 0 {
                player.play()
            }
        }
    }
}
struct _ISVideoPreviewView: UIViewRepresentable {
    @Binding var player: AVPlayer
    
    func makeUIView(context: Context) -> UIView {
        let view = AVPlayerView()
        view.layer.contentsGravity = .resizeAspect
        view.player = player
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // Do nothing here
    }
}
class AVPlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }
    
    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }
    
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}
